// 填入表格的数据
 var tableData = [];
 var ifLeft = -1;

function scatter() {
    // 选中svg
    let svg = d3.select("#scatterPoints")

    // 清空画布
    svg.selectAll( "*" )
        .remove()

    // 表头
    // svg.append( "text" )
    //     .text( "职工数据空间降维散点图" )
    //     .attr( "font-weight", "bold" )
    //     .attr( "font-size", 20 )
    //     .attr( "fill", "aqua" )
    //     .attr( "transform", "translate( 180, 30 )" )
    
    // 画图例
        // 离职人员图例组
    let lG = svg.append( 'g' )
        .attr( "id", "lG" )
        // 未离职人员图例组
    let nlG = svg.append( 'g' )
        .attr( "id", "nlG" )
        // 全体人员图例组
    let genG = svg.append( 'g' )
        .attr( "id", "genG" )

    // 未离职人员图例组绘制
    lG.append( "rect" )
        .attr( "width", 30 )
        .attr( "height", 15 )
        .attr( "fill", Color[0] )
        .attr( "transform", `translate( 440, 490 )` )
        .attr( "id", "lRect")
        // 如果被选中添加边框宽度
        .attr( "stroke-width", () => {
            if( ifLeft == 0 ) {
                return 2
            } else {
                return 0
            }
        })
        // 如果被选中突出显示边框颜色
        .attr( "stroke", () => {
            if( ifLeft == 0 ) {
                return "red"
            } else {
                return "none"
            }
        })
        // 添加文字
    lG.append( "text" )
        .text( "未离职人员" )
        .attr( "font-size", 15)
        // 如果被选中改变文字颜色
        .attr( "fill", () => {
            if ( ifLeft == 0 ) {
                return "#F53311"
            } else {
                return "#FFFFFF"
            }
        })
        .attr( "transform", `translate( 480, 503 )` )
    lG.on( "click", () => {
        ifLeft = 0;
        scatter();
    })
    
    // 离职人员图例组绘制
    nlG.append( "rect" )
        .attr( "width", 30 )
        .attr( "height", 15 )
        .attr( "fill", Color[1] )
        .attr( "transform", `translate( 440, 520 )` )
        .attr( "id", "nlRect" )
        // 如果被选中添加边框宽度
        .attr( "stroke-width", () => {
            if( ifLeft == 1 ) {
                return 2
            } else {
                return 0
            }
        })
        // 如果被选中突出显示边框颜色
        .attr( "stroke", () => {
            if( ifLeft == 1 ) {
                return "red"
            } else {
                return "none"
            }
        })
        // 添加文字
    nlG.append( "text" )
        .text( "离职人员" )
        .attr( "font-size", 15)
        // 如果被选中改变文字颜色
        .attr( "fill", () => {
            if ( ifLeft == 1 ) {
                return "#F53311"
            } else {
                return "#FFFFFF"
            }
        })
        .attr( "transform", `translate( 480, 533 )` )
    nlG.on( "click", () => {
        ifLeft = 1;
        scatter();
    })

    // 总和图例组绘制
        // 上三角部分色块
    genG.append( "path" )
        .attr( 'd', "M 440 550 l 30 0 l -30 15 l 0 -15" )
        .attr( "fill", Color[0] )
        // 如果被选中添加边框宽度
        .attr( "stroke-width", () => {
            if( ifLeft == -1 ) {
                return 2
            } else {
                return 0
            }
        })
        // 如果被选中突出显示边框颜色
        .attr( "stroke", () => {
            if( ifLeft == -1 ) {
                return "red"
            } else {
                return "none"
            }
        })
        // 下三角部分色块
    genG.append( "path" )
        .attr( 'd', "M 440 550 m 30 0 l 0 15 l -30 0 l 30 -15" )
        .attr( "fill", Color[1] )
        // 如果被选中添加边框宽度
        .attr( "stroke-width", () => {
            if( ifLeft == -1 ) {
                return 2
            } else {
                return 0
            }
        })
        // 如果被选中突出显示边框颜色
        .attr( "stroke", () => {
            if( ifLeft == -1 ) {
                return "red"
            } else {
                return "none"
            }
        })
        // 添加文字
    genG.append( "text" )
        .text( "全体人员" )
        .attr( "font-size", 15)
        // 如果被选中改变文字颜色
        .attr( "fill", () => {
            if ( ifLeft == -1 ) {
                return "#F53311"
            } else {
                return "#FFFFFF"
            }
        })
        .attr( "transform", `translate( 480, 563 )` )
    genG.on( "click", () => {
        ifLeft = -1;
        scatter();
    })
    // 引入散点数据 dsca
    d3.json( "data/json/scatterPoints.json" ).then( dsca => {
        // 引入原始数据 dori
        d3.csv( "data/csv/HR_comma_sep.csv" ).then( dori => {
            // 定义两个空数组，用于存放满足条件点的数据与序号
            let selectedData = [], selectedIndex = [];

            // 长index存字符串便于使用
            let sl = "satisfaction_level", le = "last_evaluation";
            let plfy = "promotion_last_5years", wa = "Work_accident";
            
            // 遍历将字符数据转化成数字
            dori.forEach(d => {
                d['satisfaction_level']= +(d['satisfaction_level'])
                d['last_evaluation']= +(d['last_evaluation'])
                d['average_montly_hours']= +(d['average_montly_hours'])
                d['time_spend_company']= +(d['time_spend_company'])
                d['Work_accident']= +(d['Work_accident'])
                d['promotion_last_5years']= +(d['promotion_last_5years'])
                d['left']= +(d['left'])
            });

            // 筛选出满足条件的员工
            for(let i = 0; i < dsca.length; i++) {
                if ( ifLeft == -1 ) {   // 总条件为全体员工的情况
                    if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && promotion == -1 && waccident == -1 ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    } else if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && promotion == -1 && dori[i][wa] == waccident ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    } else if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && dori[i][plfy] == promotion && waccident == -1 ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    } else if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && dori[i][plfy] == promotion && dori[i][wa] == waccident ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    }
                } else if ( ifLeft == dori[i].left) {   // 总条件为部分员工的情况
                    if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && promotion == -1 && waccident == -1 ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    } else if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && promotion == -1 && dori[i][wa] == waccident ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    } else if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && dori[i][plfy] == promotion && waccident == -1 ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    } else if ( dori[i][sl] >= minSatis && dori[i][sl] <= maxSatis && dori[i][le] >= minEvalu && dori[i][le] <= maxEvalu && dori[i][plfy] == promotion && dori[i][wa] == waccident ) {
                        selectedData.push( dori[i] )
                        selectedIndex.push( i )
                    }
                }
            }
            // console.log( selectedIndex.length )

            // 分离散点x, y轴坐标数据
            let pointX = [], pointY = [];
            for ( let i =0; i < selectedData.length; i++ ) {
                pointX.push( dsca[selectedIndex[i]][0] )
                pointY.push( dsca[selectedIndex[i]][1] )
            }

            // 定义常用量
            let conf = {
                x : 50,     // 水平平移距离
                y : 540,    // 垂直平移距离
                h : 500,    // 图画高度
                l : 500,    // 图画长度
                r : 4       // 散点半径
            }

            // x轴比例尺
            let scaleX = d3.scaleLinear()
                .domain( [d3.min( pointX ), d3.max( pointX )] )
                .range( [0, conf.l] )
            // y轴比例尺
            let scaleY = d3.scaleLinear()
                .domain( [d3.min( pointY ), d3.max( pointY )] )
                .range( [conf.h, 0] )
            
            // 作 x轴、y轴
            // let axisX = d3.axisBottom()
            //     .scale( scaleX )
            // svg.append( 'g' )
            //     .attr( "transform", `translate( ${conf.x}, ${conf.y} )` )
            //     .call( axisX )
            //     .attr( "color", "#98F5FF" )
            // let axisY = d3.axisLeft()
            //     .scale( scaleY )
            // svg.append( 'g' )
            //     .attr( "transform", `translate( ${conf.x}, ${conf.y - conf.h} )` )
            //     .call( axisY )
            //     .attr( "color", "#98F5FF" )

            // 画点
            for( let i = 0; i < selectedIndex.length; i++) {    
                // 确定散点位置
                let a = conf.x + scaleX( pointX[i] )
                let b = conf.y - scaleY( pointY[i] )
                // 定义ind便于为每个circle点添加特定id
                let ind = i

                // 画圆
                svg.append( "circle" )
                    .attr( 'cx', a )
                    .attr( 'cy', b )
                    .attr( 'r', 0 )
                    // 根据离职情况上色
                    .attr( "fill", function() {
                        if ( selectedData[ind].left == 0 ){
                            return Color[0];
                        } else {
                            return Color[1];
                        }
                    })
                    // 添加特定id
                    .attr( 'id', 'id'+selectedIndex[ind] )
                    // 判断点是否被选中并且添加点的边宽
                    .attr( 'stroke-width', () =>{
                        let jud = 0;
                        for( let j = 0; j < selectedIndex.length; j++ ) {
                            if ( selectedIndex[ind] == tableData[j] ) {
                                jud = 1;
                                break;
                            }
                        }
                        if ( jud ){
                            return 1;
                        } else {
                            return 0;
                        }
                    })
                    // 判断点是否被选中并且添加点的borde颜色
                    .attr( 'stroke', () => {
                        let jud = 0;
                        for(let j = 0; j < selectedIndex.length; j++){
                            if ( selectedIndex[ind] == tableData[j]) {
                                jud = 1;
                                break;
                            }
                        }
                        if ( jud ){
                            return 'red';
                        } else {
                            return 'none';
                        }
                    })
                    // 添加点击事件，点击选中该点
                    .on( "click", function() {
                        E = d3.select( this )
                            .attr( 'stroke-width', 1 )
                            .attr( 'stroke', 'red' )
                        EV = Number( this.id.slice(2) )
                        if ( !( tableData.includes( EV ) ) ){
                            tableData.push( EV )
                            tableActive();
                            parCoo();
                        }
                        // console.log( EV, tableData, tableData.includes( EV ) )
                    })
                    // 添加动画效果
                    .transition()
                    .duration( 1500 )
                    .attr( "r", conf.r + 5 )
                    .transition()
                    .duration( 1000 )
                    .attr( "r", conf.r )
            }

            // 定义变量储存每个多边形顶点
            let x1,y1;
            //多边形顶点数组
            let shapePath = []

            // d3.line函数提取
            let linePath = d3.line()

            // 为svg添加鼠标按下事件
            svg.on("mousedown",function(){
                drawLine = svg.append( 'g' )
                    .attr( "id", "drawLine")
                // 记录初始点
                x1 = window.event.offsetX
                y1 = window.event.offsetY
                shapePath.push( [x1, y1] )
                sPtX = x1;
                sPtY = y1;
                // 鼠标按下后为svg添加鼠标移动事件，获取画每个的点，和line数组
                svg.on("mousemove",function(){
                    // 获取多边形顶点并放入数组
                    let x3 = window.event.offsetX
                    let y3 = window.event.offsetY
                    shapePath.push( [x3, y3] )
                    // drawLine.remove( '*' )

                    // 实时绘制曲线
                    drawLine.append( "path" )
                            .attr( 'd', linePath( shapePath ) )
                            .attr( "fill", "none" )
                            .attr( "stroke-width", 1)
                            .attr( "stroke", "aqua")
                    // console.log(linePath( shapePath ))
                })
            })
            // 鼠标弹起时结束事件
            .on("mouseup",function(){
                // 移除鼠标移动事件
                svg.on( "mousemove", () => {})

                //清空轨迹
                drawLine.remove()

                // 连接轨迹首尾
                shapePath.push( [x1, y1] )
                // console.log(linePath( shapePath ))

                // 选取范围内的点
                for( let i=1; i < selectedIndex.length; i++ ) {
                    // 获取每个点的位置
                    let a = conf.x + scaleX( pointX[i] )
                    let b = conf.y - scaleY( pointY[i] )

                    // 通过innerOrOuter()函数判断点是否位于多边形内
                    if ( innerOrOuter( [a, b], shapePath ) ) {
                        if ( !( tableData.includes( selectedIndex[i] ) ) ){
                            // 将位于多边形框选范围内的序号index加入被选择点数组
                            tableData.push( selectedIndex[i] )

                            // 为被选中的点添加特定id
                            d3.select( "#id" + selectedIndex[i] )
                                .attr( 'stroke-width', 1 )
                                .attr( 'stroke', 'red' )
                        }
                    }
                }

                // 重运行与散点图有交互的图表
                tableActive();
                parCoo();
                draw_stackedbar();
                reqHis();
                draw_barchart();
                draw_piechart();
                
                // console.log(shapePath)
                // 清空多边形
                shapePath = []
                shapePath.length = 0
                // console.log(shapePath)
            })
        })
    })
}